package org.particlethink.mapper.impl;

import org.particlethink.config.RequestConfig;
import org.particlethink.context.Context;
import org.particlethink.mapper.MaterialMapper;
import org.particlethink.model.Material;
import org.particlethink.model.Supplier;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.stereotype.Repository;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Repository
//@ConditionalOnMissingBean(DevMaterialMapperImpl.class)
@ConditionalOnExpression("#{!'dev'.equals('${spring.profiles.active}')}")
public class ProMaterialMapperImpl implements MaterialMapper {

    @Autowired
    private RequestConfig requestConfig;

    @Override
    public List<Material> selectByIds(String token, List<Integer> ids) {
        return this.fetch(token, ids, new ArrayList<>(), new ArrayList<>(), 1, 20).stream().filter(item -> ids.contains(item.getId())).collect(Collectors.toList());
    }


    @Override
    public List<Material> all(String token) {
        return this.fetch(token, new ArrayList<>(), new ArrayList<>(), new ArrayList<>(), 1, 20);
    }

    @Override
    public Material selectById(String token, int materialId) {
        ArrayList<Integer> ids = new ArrayList<>();
        ids.add(materialId);
        return this.selectByIds(token, ids).stream().filter(item -> item.getId().equals(materialId)).findFirst().orElse(null);
    }

    @Override
    public List<Material> selectByNos(String token, List<String> codes) {
        return this.fetch(token, new ArrayList<>(), new ArrayList<>(), codes, 1, 20);
    }

    @Override
    public List<Supplier> selectByParentCategoryId(String token, String parentCategoryCode) {
        try {

            return ProMaterialRequestHelper.suppliersByParentCategoryId(parentCategoryCode, requestConfig.getUrl(), token);
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }


    private List<Material> fetch(String token, List<Integer> ids, List<String> materialCodes, List<String> codes, Integer pageNum, Integer pageSize) {
        List<Material> materials = new ArrayList<>();

        try {

            ProMaterialRequestHelper.MaterialResponse resp = ProMaterialRequestHelper.listMaterials(
                    requestConfig.getUrl(),
                    token,
                    ids,
                    materialCodes,
                    codes,
                    pageNum,
                    pageSize
            );

            if (resp.getRows() == null || resp.getRows().isEmpty()) {
                return new ArrayList<>();
            }

            resp.getRows().forEach(material -> {
                String categoryName;
                String parentCategoryName;
                String[] cate = material.getType().split("-");
                if (cate.length == 2) {
                    categoryName = cate[1];
                    parentCategoryName = cate[0];
                } else {
                    parentCategoryName = "";
                    categoryName = "";
                }

                if (material.getMaterialDetails() == null || material.getMaterialDetails().isEmpty()) {
                    return;
                }
                material.getMaterialDetails().forEach(requestMaterial -> {

                    Material material1 = new Material();
                    material1.setId(requestMaterial.getId());
                    material1.setName(requestMaterial.getName());
                    material1.setQuality(requestMaterial.getQualityStandard());
                    material1.setSpecification(requestMaterial.getSpecification());
                    material1.setNo(requestMaterial.getCode());
                    material1.setUnit(requestMaterial.getUnit());
                    material1.setTyp(requestMaterial.getModel());

                    material1.setCategoryId(requestMaterial.getCategoryId());
                    material1.setParentCategoryId(requestMaterial.getParentCategoryId());

                    material1.setAllCategory(requestMaterial.getMaterialDetail());


                    material1.setParentCategoryName(categoryName);
                    material1.setCategoryName(parentCategoryName);
                    materials.add(material1);

                });
            });
        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }

        return materials;
    }


    public ProMaterialRequestHelper.MaterialResponse Find(String token, List<Integer> ids, List<String> materialCodes, List<String> codes, Integer pageNum, Integer pageSize) {

        try {
            return ProMaterialRequestHelper.listMaterials(
                    requestConfig.getUrl(),
                    token,
                    ids,
                    materialCodes,
                    codes,
                    pageNum,
                    pageSize
            );


        } catch (URISyntaxException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}


